package com.fans.common.redis;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fans.common.redis.util.RedisObjectSerializer;

/**
 * @ClassName: RedisConfig
 * @Description: redis 配置
 * @author fanhaohao
 * @date 2019年12月5日 下午3:18:42
 */
@Configuration
public class RedisConfig {

	/**
	 * @Title：getRedisTemplate
	 * @Description: redis 集群模式
	 * @author: fanhaohao
	 * @date 2019年12月7日 下午5:40:36
	 * @param @param factory
	 * @param @return
	 * @return RedisTemplate<String,Object>
	 * @throws
	 */
	@Primary
	@Bean("redisTemplate")
	@ConditionalOnProperty(name = "spring.redis.cluster.nodes", matchIfMissing = false)
	public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
		redisTemplate.setConnectionFactory(factory);
		RedisSerializer stringSerializer = new StringRedisSerializer();
		RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
		redisTemplate.setKeySerializer(stringSerializer); // key的序列化类型
		redisTemplate.setHashKeySerializer(stringSerializer);
		redisTemplate.setValueSerializer(redisObjectSerializer); // value的序列化类型
		redisTemplate.afterPropertiesSet();
		redisTemplate.opsForValue().set("hello", "wolrd");
		return redisTemplate;
	}

	/**
	 * @Title：getSingleRedisTemplate
	 * @Description: reids 单机模式
	 * @author: fanhaohao
	 * @date 2019年12月7日 下午5:40:52
	 * @param @param factory
	 * @param @return
	 * @return RedisTemplate<String,Object>
	 * @throws
	 */
	@Primary
	@Bean("redisTemplate")
	@ConditionalOnProperty(name = "spring.redis.host", matchIfMissing = true)
	public RedisTemplate<String, Object> getSingleRedisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
		redisTemplate.setConnectionFactory(factory);
		redisTemplate.setKeySerializer(new StringRedisSerializer()); // key的序列化类型
		redisTemplate.setValueSerializer(new RedisObjectSerializer()); // value的序列化类型
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}

}
